package com.heiyu.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class RedisUtils {

    private final static Logger logger = LoggerFactory.getLogger(RedisUtils.class);

    @Autowired
    private  JedisPool pool;

    // 设置对象持久化
    public  String set(final String key, final String val) {
        Jedis jedis = pool.getResource();
        String result = jedis.set(key, val);
        jedis.close();
        return result;
    }

    public String hget(final String key,final String field){
        Jedis jedis = pool.getResource();
        String result = jedis.hget(key, field);
        jedis.close();
        return result;
    }

    // 设置对象存活时间 time单位秒
    public  void set(final String key, final String val, final int time) {
        try {
            Jedis jedis = pool.getResource();
            jedis.setex(key, time, val);
            jedis.close();
        } catch (Exception e) {
            logger.error("设置定时cache错误", e);
        }
    }

    // 获取对象
    public  String get(final String key) {
        Jedis jedis = pool.getResource();
        String s = jedis.get(key);
        jedis.close();
        return s;
    }

    // 计数器
    public  Long incr(final String key) {
        Jedis jedis = pool.getResource();
        Long l = jedis.incr(key);
        jedis.close();
        return l;
    }

    // 删除对象
    public  void del(final String key) {
        Jedis jedis = pool.getResource();
        jedis.del(key);
        jedis.close();
    }
}
